import uvicorn
import time

from fastapi import FastAPI, Request
import psycopg2
import redis

conn = psycopg2.connect(
    host='211.103.77.22',
    port='15432',
    dbname='smart_switch_monitor',
    user='patrol',
    password='RXeVmMTWkrm3pj9'
)

cache = redis.Redis(host='211.103.77.22', port=16379, db=0, password='v45koDcqEIWMwC23')

app = FastAPI()


@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response


@app.get("/")
def read_root():
    cursor = conn.cursor()
    cursor.execute('select * from t_sys_users')
    rows = cursor.fetchall()
    get = cache.get("snowflake_15")
    return (rows,get)


if __name__ == "__main__":
    uvicorn.run("middleware_demo:app")
